package br.usp.ime.components.daos;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import br.com.caelum.vraptor.ioc.ApplicationScoped;
import br.com.caelum.vraptor.ioc.Component;
import br.usp.ime.entities.Evaluation;

@Component
@ApplicationScoped
public class EvaluationDao {

    private final Session session;

    public EvaluationDao(Session session) {
        this.session = session;
    }

    public void addEvaluation(Evaluation evaluation) {
        Transaction tx = this.session.beginTransaction();
        this.session.save(evaluation);
        tx.commit();
    }

    public void updateEvaluation(Evaluation evaluation) {
        if (evaluationExists(evaluation)) {
            Transaction tx = this.session.beginTransaction();
            this.session.merge(evaluation);
            tx.commit();
        }
    }

    public Evaluation loadEvaluation(Evaluation evaluation) {
        if (evaluation == null)
            return null;
        session.clear();
        return (Evaluation) session.createCriteria(Evaluation.class)
                .add(Restrictions.eq("id", evaluation.getId())).uniqueResult();
    }

    public void deleteEvaluation(Evaluation evaluation) {
        Evaluation deletedEvaluation = loadEvaluation(evaluation);
        if (deletedEvaluation != null) {
            Transaction tx = this.session.beginTransaction();
            this.session.delete(deletedEvaluation);
            tx.commit();
        }
    }

    private boolean evaluationExists(Evaluation evaluation) {
        return loadEvaluation(evaluation) != null;
    }

}
